package com.smart.thrift.util;

import lombok.extern.slf4j.Slf4j;

import java.net.*;
import java.util.Enumeration;
import java.util.regex.Pattern;

@Slf4j
public class IPUtil {
    public static final String getLocalAddress(Pattern blackList) throws UnknownHostException, SocketException {
        String svrName = InetAddress.getLocalHost().getHostName();
        //IP
        Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
        while (netInterfaces.hasMoreElements()) {
            NetworkInterface netInterface = (NetworkInterface) netInterfaces.nextElement();
            Enumeration addresses = netInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress ip = (InetAddress) addresses.nextElement();
                if (ip instanceof Inet4Address && !ip.isLoopbackAddress()) {
                    String svrIP = ip.getHostAddress();
                    if (blackList == null || !blackList.matcher(svrIP).matches()) {
                        return svrIP;
                    }
                }
            }
        }
        return svrName;
    }
}
